<template>
    <div>
        <Row class="topBar">
            <Col span="4" style="padding-left:10px">角色管理</Col>

            <Col span="2" offset="18">
                <Button @click="showRole" class="btn-in-top-large" style="margin-right:0px" type="primary" v-pmis="32">添加角色</Button>
            </Col>
        </Row>

        <Table :loading="isLoading" border :columns="columns1" :data="data2">

        </Table>


        <Page
            @on-change="pageChange"
            :total="total"
            :page-size="limit"
            show-elevator
            show-total
            style="text-align:center">
        </Page>

        <roleModal
            :role-type="currentRole.type"
            :title="currentRole.actionTitle"
            :role-id="currentRole.id"
            :modal="roleModalVisible"
            @update-list="updateList"
            :roles="data2"
            @update="val => roleModalVisible = val">
        </roleModal>

        <Modal v-model="modal" class-name="vertical-center-modal" title="以下员工正在使用该角色,请更改员工角色后删除">
            <div class="clear-fix role-users-wrap">
                <div v-for="item in roleUsers" :key="item.telephone" class="role-users">
                    {{item.name}} - {{item.telephone}}
                </div>
            </div>
            <p slot="footer" style="text-align:center">
                <Button type="primary" @click="close()">确 定</Button>
            </p>
        </Modal>
    </div>
</template>

<script>
import roleModal from './roleModal.vue'
import { http, api } from '@/libs/http'
import { mapState } from 'vuex'
export default {
  data () {
    return {
      modal: false,
      limit: 20,
      total: 0,
      offset: 1,
      cal: '',
      currentRole: {
        actionTitle: '',
        id: '',
        type: ''
      },
      roleModalVisible: false,
      isLoading: true,
      roleId: '',
      columns1: [
        {
          align: 'center',
          title: '角色',
          key: 'name'
        },
        {
          align: 'center',
          title: '类型',
          key: 'roleName'
        },
        {
          align: 'center',
          title: '时间',
          render: (h, params) => {
            return h('span', new Date(params.row.updated_at).Format('yyyy-MM-dd HH:mm'))
          }
        },
        {
          align: 'center',
          title: '操作',
          key: 'action',
          render: (h, p) => {
            const base = {
              props: { type: 'ghost', size: 'small' },
              style: { marginRight: '5px' }
            }
            const isNotBaseRole = p.row.type !== 0
            return (
              <div>
                <i-button {...base} onClick={() => this.check(p.row)}>查看</i-button>
                {
                  isNotBaseRole && <i-button {...base} onClick={() => this.editRole(p.row)}>编辑</i-button>
                }
                {
                  isNotBaseRole && <i-button {...base} onClick={() => this.delRole(p)}>删除</i-button>
                }
              </div>
            )
          }
        }
      ],
      data2: [],
      roleUsers: []
    }
  },
  computed: {
    permissions () {
      if (localStorage.permission) {
        return JSON.parse(localStorage.permission)
      } else {
        return {}
      }
    },
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    })
  },
  methods: {
    close () {
      this.modal = false
    },
    userPage () {
      this.modal = false
      this.$emit('updateName', 'name1')
    },
    // 分页
    pageChange (val) {
      this.offset = val
      this.getRoles()
    },
    // 更新列表
    updateList () {
      this.getRoles()
    },
    showRole () {
      this.setRoleModal('添加角色', null, null)
    },
    // 查看
    check (row) {
      const { type, id } = row
      this.setRoleModal('查看角色', type, id)
    },
    // 编辑角色
    editRole (row) {
      // console.log(row);
      const { type, id } = row
      this.setRoleModal('编辑角色', type, id)
    },
    setRoleModal (actionTitle, type, id) {
      this.roleModalVisible = true
      this.currentRole = { actionTitle, type, id }
    },
    // 删除角色
    delRole (params) {
      // 先检查角色下是否有用户
      let obj = {
        role_id: params.row.id
      }
      http.request(this, api.user_list, null, obj, (res, err) => {
        // 有用户
        this.roleUsers = res.rows
        if (res && res.rows.length) {
          this.modal = true
        } else {
          // 没有用户
          this.$Modal.confirm({
            title: '删除角色',
            content: '确定要删除该角色吗?',
            okText: '删除',
            onOk: () => {
              this.delRoleConfirm(params.row.id)
            }
          })
        }
      })
    },
    delRoleConfirm (id) {
      const msg = this.$Message.loading({
        content: '删除角色中...',
        duration: 0
      })
      http.request(this, api.role_del, [id], null, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('删除角色成功!')
        msg()
        this.getRoles()
      })
    },
    // 获取角色列表
    getRoles () {
      this.isLoading = true
      let obj = {
        offset: (this.offset - 1) * this.limit,
        limit: this.limit,
        list_type: 'page'
      }
      http.request(this, api.role_list, null, obj, (res, err) => {
        if (res) {
          this.total = res.count - 1
          const data2 = []
          res.rows.forEach(item => {
            if (item.id !== 100) {
              switch (item.type) {
                case 0:
                  if (this.hasFaceAccessPermission || item.name !== '保安') {
                    item.roleName = '经典角色'
                    data2.push(item)
                  }
                  break
                case 1:
                  item.roleName = '自定义角色'
                  data2.push(item)
                  break
              }
            }
          })
          this.data2 = data2.sort((a, b) => {
            return a.id - b.id
          })
        }
        this.isLoading = false
      })
    }
  },
  created () {
    this.getRoles()
  },
  components: {
    roleModal
  }
}
</script>

<style lang="less">
.topBar {
    color: #1c2438;
    font-size: 18px;
    line-height: 50px;
    width: 100%;
    height: 50px;
    background: #efeff1;
    border-left: 5px solid #05bac5;
    margin-bottom: 20px;
}
.role-users {
    line-height: 2.2;
    text-align: center;
    width: 50%;
    float: left;
}
</style>
